package com.tanhua.manage.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.AdminMapper;
import com.tanhua.common.pojo.Admin;
import com.tanhua.common.utils.AdminThreadLocal;
import com.tanhua.manage.vo.ManageVo;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ManageUserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AdminMapper adminMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private Verification verification;


    public BufferedImage getVf(String uuid) {

        //根据随机数生成图片
        BufferedImage img = verification.getImg(uuid);

        return img;
    }

    public Map<String, Object> login(String username, String password, String verificationCode, String uuid) {

        //校验验证码
//        String random = (String) redisTemplate.opsForValue().get(uuid);
//        if (random.isEmpty()) {
//            return null;
//        }
//        if (!random.equals(verificationCode)) {
//            return null;
//        }

        //this.redisTemplate.delete(uuid);

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).eq("password", password);
        Admin admin = this.adminMapper.selectOne(queryWrapper);
        if (null == admin) {
            return null;
        }

        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", admin.getId());
        String redisKey = "TANHUA_ADMIN_ID_" + admin.getId();
        this.redisTemplate.opsForValue().set(redisKey, username, Duration.ofHours(12));

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        return result;

    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public Admin queryAdminToken(String token) {
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            Admin admin = new Admin();
            Long id = Long.valueOf(body.get("id").toString());

            //需要返回user对象中的mobile，需要查询数据库获取到mobile数据
            //如果每次都查询数据库，必然会导致性能问题，需要对用户的手机号进行缓存操作
            //数据缓存时，需要设置过期时间，过期时间要与token的时间一致
            //如果用户修改了手机号，需要同步修改redis中的数据

            String redisKey = "TANHUA_ADMIN_ID_" + id;
            //在jwt中的过期时间的单位为：秒
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            String username = this.redisTemplate.opsForValue().get(redisKey);
            admin.setId(id);
            admin.setUsername(username);
            return admin;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            log.error("token不合法！ token = " + token, e);
        }
        return null;
    }

    public Boolean logOut() {
        Admin admin = AdminThreadLocal.get();

        String redisKey = "TANHUA_ADMIN_ID_" + admin.getId();
        Boolean delete = this.redisTemplate.delete(redisKey);
        return delete;
    }

    /**
     * 查看信息
     *
     * @return
     */
    public ManageVo profile() {

//        Admin admin = AdminThreadLocal.get();
        Admin admin = new Admin();
        admin.setUsername("admin");
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,admin.getUsername());
        Admin admin1 = this.adminMapper.selectOne(queryWrapper);
        ManageVo manageVo = new ManageVo();
        manageVo.setUid(admin1.getId().toString());
        manageVo.setUsername(admin1.getUsername());
        manageVo.setAvatar(admin1.getAvatar());
        return manageVo;
    }
}